<template>
  <div class="mb-sub-grid">
    <!-- 编辑模式 -->
    <template v-if="!readonly">
      <van-cell :title="title" is-link @click="subgridClick"/>
      <van-popup 
        v-model="showPopup" 
        position="right"
        get-container="body" 
        :style="{ width: '100%', height: '100%' }"
      >
        <van-nav-bar
          :title="title"
          left-arrow
          @click-left="showPopup = false"
        />
        <div class="sub-grid">
          <div class="sub-grid-group van-hairline--bottom" v-for="(item, index) in subGridList" :key="index">
            <div class="form-card-title van-hairline--bottom" style="text-align: right;">
              <a href="javascript:void(0)" class="sub-grid-action" @click="delAction(item, index)">{{deltext}}</a>
            </div>
            <div class="sub-grid-cell" :id="item.uid"></div>
          </div>
          <div class="sub-grid-add">
            <span class="sub-grid-action" @click="addAction"><van-icon name="plus" />{{addText}}</span>
          </div>
        </div>
        <van-button type="info" block @click="onConfirm">{{confirmText}}</van-button>
      </van-popup>
    </template>
    <!-- 只读模式 -->
    <template v-else>
      <van-cell-group 
        v-for="(item, index) in readonlyMeta"
        class="cell-group-readonly" 
        :title="subGridTitle + (index + 1)"
        :key="index">
        <van-field 
          v-for="(opt, key) in item"
          :key="key"
          :label="opt.caption || opt.name" 
          :value="opt.defaultValue_display || opt.defaultValue" 
          readonly />
      </van-cell-group>
    </template>
  </div>
</template>

<script>
import { MbCell, MbField, MbSelect,  MbSwitcher, MbDatetimePicker, MbUploader} from "mb-vue"
import compiler from "utils/compiler"
const components = { MbCell, MbField, MbSelect,  MbSwitcher, MbDatetimePicker, MbUploader}

/*!
 * 该组件为数据处理层，用于数据分发，对接组件
 *
 */
export default {
  name: 'mb-sub-grid',
  data () {
    return {
      meta: [],
      readonlyMeta: [],
      model: [],
      showPopup: false,
      deltext: '删除',
      subGridList: [],
      subGridListVM: [],
      addText: '添加',
      confirmText: '确定',
      formData: [],
      defaultValue: [],
      defaultValueModel: []
    }
  },
  props: {
    options: Object,
    readonly: Boolean
  },
  computed: {
    title() {
      return this.options.name + " ( " + this.options.meta.name + " ) "
    },
    subGridTitle() {
      return  this.options.meta.name
    },
    subgridId() {
      return this.options.key
    }
  },
  methods: {
    init() {
      if(!this.options.meta) return;

      // 非只读模式 -- 按照 [options.model] 顺序整合 [meta.ref] 数据顺序
      const _this = this;
      this.model = this.options.options.models;
      const metaHash = new Array();
      this.options.meta.ref.forEach( item => {
        item.supportSigns = _this.options.supportSigns;
        item.time = _this.options.time;
        metaHash[item.name] = item
      });
      this.meta = [];
      this.model.forEach( item => {
        this.meta.push(metaHash[item]);
      });


      if(this.options.defaultValue) {
        this.defaultValue = this.options.defaultValue[this.options.meta.name] || [];
        this.subGridList = JSON.parse(JSON.stringify(this.defaultValue));
        this.subGridList = this.subGridList.map((item) => {
          item.uid = "sub-grid-" + this.getUID();
          let metaModel = JSON.parse(JSON.stringify(this.meta));
          metaModel = metaModel.map((meta) => {
            meta.defaultValue = item[meta.name];
            if(item[(meta.name + "_DISPLAY")]) meta.defaultValue_display = item[(meta.name + "_DISPLAY")];
            return meta
          })
          this.defaultValueModel.push(metaModel);
          return item
        })
      }


      // 只读模式,处理[option.defaultValue]
      if(this.readonly) {
        if(this.defaultValue && this.defaultValue.length) {
          // 针对只读，将defaultValue与this.meta匹配上，组装出新的数组用来v-for
          this.readonlyMeta = [];
          this.defaultValue.forEach( item => {
            let meta = Object.assign([], this.meta);
            meta = meta.map(opt => {
              opt.defaultValue = item[opt.name]
              if(item[opt.name + "_DISPLAY"] != null) {
                opt["defaultValue_display"] = item[opt.name + "_DISPLAY"]
              }
              return opt
            })
            this.readonlyMeta.push(meta)
          })
        }
        return
      }
    },
    subgridClick() {
      this.showPopup = true;
      if(!this.subGridListVM.length){
        const _this = this;
        this.$nextTick(function(){
          this.subGridList.forEach((item, index) => {
            let vm = compiler(this.defaultValueModel[index], components, "#" + item.uid);
            this.subGridList[index] = vm.formData;
            this.subGridListVM.push(vm);
            vm.$on('formdataChange', function () {
              let emitObj = {};
              emitObj[_this.options.meta.name] = _this.subGridList;
              _this.$emit("subgridChange", _this.options.meta.name, emitObj, _this.options.meta)
            })
          });
        })
      }
    },
    addAction() {
      let uid = "sub-grid-" + this.getUID();
      let newObj = { uid: "sub-grid-" + uid };
      this.model.forEach(item => {
        newObj[item] = null;
      })
      this.subGridList.push(newObj);
      const _this = this;
      this.$nextTick(function(){
        let vm = compiler(this.meta, components, "#" + newObj.uid);
        this.subGridList[this.subGridList.length - 1] = vm.formData;
        this.subGridListVM.push(vm);
        vm.$on('formdataChange', function () {
          let emitObj = {};
          emitObj[_this.options.meta.name] = _this.subGridList;
          _this.$emit("subgridChange", _this.options.meta.name, emitObj, _this.options.meta)
        })
      })
    },
    delAction(item, index) {
      const _this = this;
      this.subGridList.splice(index, 1);
      let delVM = this.subGridListVM.splice(this.subGridListVM.length -1)[0];
      delVM.$off();
      delVM.$destroy();
      this.subGridList.forEach((option, key) => {
        _this.subGridListVM[key].setFormValues(option);
      })
      let emitObj = {};
      emitObj[this.options.meta.name] = this.subGridList;
      this.$emit("subgridChange", _this.options.meta.name, emitObj, this.options.meta)
    },
    onConfirm() {
      this.showPopup = false;
    },
    getUID () {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        let r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
      });
    },
  },
  mounted () {
    this.init()
  }
}
</script>
<style>
.sub-grid {
  background-color: #F9F9F9;
  max-height: calc(100vh - 90px);
  overflow: auto;
}
.sub-grid-action {
  display: inline-block;
  color: #1989fa;
}
.sub-grid-add {
  padding: 12px 10px;
}
</style>
